//
//  CHWebViewController.swift
//  bridging_js
//
//  Created by cyptt on 2021/7/28.
//

import UIKit
import WebKit

public protocol CHWebDelegate{
    func dunInit()
}
public extension CHWebDelegate{
    func dunInit(){
        
    }
}

public class CHWebViewController: UIViewController{
  
    var webUrl:String?
    var miSLocal:Bool?
    
    var chwebdelegate:CHWebDelegate?
    var webView = WKWebView()
   public override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.white
        
        //加载webview 根据url

       webView = CHWebView(controller: self, frame:  CGRect(x: 0,y: 0,width: self.view.frame.width,height: self.view.frame.height), configuration: WKWebViewConfiguration(),webDelegate: self.chwebdelegate)
        webView.backgroundColor = UIColor.red
        
        self.view.addSubview(webView)
        
        if miSLocal! {
            
            let path = Bundle.main.bundlePath
            print(path)
            let url = URL.init(fileURLWithPath: path)
            
            webView.loadHTMLString(webUrl!, baseURL: url)
        
        }else{
            
            let url = URL(string: webUrl!)
            //创建请求
            let request = URLRequest(url: url!)
    
            //加载请求
            webView.load(request)
           
        }
       
       
    }
    
  
    
    /**
     url:url地址
     isLocal:是否是本地web true 本地
     */
    public init(url:String,isLocal:Bool,webDelegate:CHWebDelegate? = nil) {
        super.init(nibName: nil, bundle: nil)
        self.chwebdelegate = webDelegate;
        
        webUrl = url
        miSLocal = isLocal
    
    }
    
 
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
  
  public  override func viewDidDisappear(_ animated: Bool) {
        clearCache()
    }
    
    func clearCache() {
            if #available(iOS 9.0, *) {
                let websiteDataTypes = NSSet(array: [WKWebsiteDataTypeDiskCache, WKWebsiteDataTypeMemoryCache])
                let date = NSDate(timeIntervalSince1970: 0)
                WKWebsiteDataStore.default().removeData(ofTypes: websiteDataTypes as! Set<String>, modifiedSince: date as Date, completionHandler:{ })
            } else {
                var libraryPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.libraryDirectory, FileManager.SearchPathDomainMask.userDomainMask, false).first!
                libraryPath += "/Cookies"
                
                do {
                    try FileManager.default.removeItem(atPath: libraryPath)
                } catch {
                    print("error")
                }
                URLCache.shared.removeAllCachedResponses()
            }
        }
 
   

}
